package com.robot.admin.controller;

import com.alibaba.fastjson.JSON;
import com.robot.admin.client.AdClient;
import com.robot.admin.pojo.client.Banner;
import com.robot.admin.service.AdminService;
import entity.Result;
import entity.StatusCode;
import io.jsonwebtoken.Claims;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import util.CheckUtil;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.Map;

/**
 * 轮播图模块
 *
 * @author lin
 */
@RestController
@CrossOrigin
@RequestMapping("/banner")
public class BannerController {
    @Autowired
    private AdminService adminService;

    @Autowired
    private AdClient adClient;

    @Autowired
    private CheckUtil checkUtil;

    @Autowired
    private HttpServletRequest request;

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    /**
     * 轮播图类型
     */
    private final String bannerTypeImage = "0";
    private final String bannerTypeVideo = "1";


    /**
     * 轮播图列表-条件查询
     *
     * @param searchMap 查询条件封装
     * @param page      页码
     * @param size      页大小
     * @return 分页结果``
     */
    @RequestMapping(value = "findBannerBySearch/{page}/{size}", method = RequestMethod.POST, produces = "application/json;charset=utf-8")
    public Result findBannerBySearch(@RequestBody Map searchMap, @PathVariable int page, @PathVariable int size) {
        Claims claims = (Claims) request.getAttribute("robot_admin");
        if (claims == null) {
            return new Result(StatusCode.ERROR_TOKEN_EXPIRED);
        }
        logger.info("claims.getId()=" + claims.getId());
        //前端调用findByToken接口检查过了,所以这里不再对管理员是否存在和状态进行判断

        return new Result(StatusCode.SUCCESS_QUERY, JSON.parseObject(adClient.thirdFindBannerBySearch(searchMap, page, size)));
    }

    /**
     * 根据ID查询轮播图详情
     *
     * @param id ID
     * @return
     */
    @RequestMapping(value = "findBannerById/{id}", method = RequestMethod.GET, produces = "application/json;charset=utf-8")
    public Result findBannerById(@PathVariable String id) {
        Claims claims = (Claims) request.getAttribute("robot_admin");
        if (claims == null) {
            return new Result(StatusCode.ERROR_TOKEN_EXPIRED);
        }
        logger.info("claims.getId()=" + claims.getId());
        //前端调用findByToken接口检查过了,所以这里不再对管理员是否存在和状态进行判断

        Banner bannerInDb = JSON.parseObject(adClient.thirdFindBannerById(id), Banner.class);
        logger.info("bannerInDb=" + bannerInDb);
        String message = checkPojo(bannerInDb);
        if (!"".equals(message)) {
            return new Result(StatusCode.ERROR, message);
        }

        return new Result(StatusCode.SUCCESS_QUERY, bannerInDb);
    }

    /**
     * 增加轮播图
     *
     * @param banner
     */
    @RequestMapping(value = "addBanner", method = RequestMethod.POST, produces = "application/json;charset=utf-8")
    public Result addBanner(@RequestBody Banner banner) {
        Claims claims = (Claims) request.getAttribute("robot_admin");
        if (claims == null) {
            return new Result(StatusCode.ERROR_TOKEN_EXPIRED);
        }
        logger.info("claims.getId()=" + claims.getId());
        //前端调用findByToken接口检查过了,所以这里不再对管理员是否存在和状态进行判断

        logger.info("banner=" + banner);
        if (banner.getTitle() == null || "".equals(banner.getTitle())) {
            return new Result(StatusCode.ERROR_BANNER_TITLE_REQUIRED);
        }
        if (banner.getType() == null || "".equals(banner.getType())) {
            return new Result(StatusCode.ERROR_BANNER_TYPE_REQUIRED);
        }
        if (!bannerTypeImage.equals(banner.getType()) && !bannerTypeVideo.equals(banner.getType())) {
            return new Result(StatusCode.ERROR_BANNER_TYPE_INVALID);
        }
        if (banner.getImageUrl() == null || "".equals(banner.getImageUrl())) {
            return new Result(StatusCode.ERROR_BANNER_IMAGE_URL_REQUIRED);
        }

        if (!checkUtil.checkImage(banner.getImageUrl())) {
            return new Result(StatusCode.ERROR, "请输入正确格式的轮播图图片");
        }
        logger.info("status=" + banner.getStatus());
        /**
         * 轮番图的状态
         */
        String bannerStatusDisable = "0";
        String bannerStatusEnable = "1";
        if (banner.getStatus() == null || "".equals(banner.getStatus())) {
            banner.setStatus(bannerStatusEnable);
        } else if (!bannerStatusDisable.equals(banner.getStatus()) && !bannerStatusEnable.equals(banner.getStatus())) {
            banner.setStatus(bannerStatusEnable);
        }

        adClient.thirdAddBannerByBanner(JSON.toJSONString(banner));
        return new Result(StatusCode.SUCCESS_INSERTED);
    }

    /**
     * 修改轮播图
     *
     * @param banner
     */
    @RequestMapping(value = "updateBanner/{id}", method = RequestMethod.PUT, produces = "application/json;charset=utf-8")
    public Result updateBanner(@RequestBody Banner banner, @PathVariable String id) {
        Claims claims = (Claims) request.getAttribute("robot_admin");
        if (claims == null) {
            return new Result(StatusCode.ERROR_TOKEN_EXPIRED);
        }
        logger.info("claims.getId()=" + claims.getId());
        //前端调用findByToken接口检查过了,所以这里不再对管理员是否存在和状态进行判断

        logger.info("banner=" + banner);
        Banner bannerInDb = JSON.parseObject(adClient.thirdFindBannerById(id), Banner.class);
        logger.info("bannerInDb=" + bannerInDb);
        String message = checkPojo(bannerInDb);
        if (!"".equals(message)) {
            return new Result(StatusCode.ERROR, message);
        }

        if (banner.getImageUrl() != null && !"".equals(banner.getImageUrl())) {

            if (!checkUtil.checkImage(banner.getImageUrl())) {
                return new Result(StatusCode.ERROR, "请输入正确格式的轮播图图片");
            }
        }

        bannerInDb = updatePojo(banner, bannerInDb);

        adClient.thirdUpdateBannerByBanner(JSON.toJSONString(bannerInDb));
        return new Result(StatusCode.SUCCESS_UPDATED);
    }

    /**
     * 删除轮播图
     *
     * @param id
     */
    @RequestMapping(value = "deleteBannerById/{id}", method = RequestMethod.PUT, produces = "application/json;charset=utf-8")
    public Result deleteBannerById(@PathVariable String id) {
        Claims claims = (Claims) request.getAttribute("robot_admin");
        if (claims == null) {
            return new Result(StatusCode.ERROR_TOKEN_EXPIRED);
        }
        logger.info("claims.getId()=" + claims.getId());
        //前端调用findByToken接口检查过了,所以这里不再对管理员是否存在和状态进行判断

        Banner bannerInDb = JSON.parseObject(adClient.thirdFindBannerById(id), Banner.class);
        logger.info("bannerInDb=" + bannerInDb);
        String message = checkPojo(bannerInDb);
        if (!"".equals(message)) {
            return new Result(StatusCode.ERROR, message);
        }

        bannerInDb.setDeletedAt(LocalDateTime.now());
        adClient.thirdUpdateBannerByBanner(JSON.toJSONString(bannerInDb));
        return new Result(StatusCode.SUCCESS_DELETED);
    }


    @RequestMapping(value = "/findBannersByStatus/{status}", method = RequestMethod.GET)
    public Result thirdFindBannersByStatus(@PathVariable String status) {
        return new Result(StatusCode.SUCCESS_QUERY, JSON.parseObject(adClient.thirdFindBannersByStatus(status)));
    }

    /**
     * 检查实体类是否存在
     *
     * @param bannerInDb
     * @return
     */
    public String checkPojo(Banner bannerInDb) {
        if (bannerInDb == null) {
            return ("该条轮播图不存在");
        }
        if (bannerInDb.getDeletedAt() != null) {
            return ("该条轮播图已被删除");
        }
        return "";
    }

    /**
     * update时更新实体类
     *
     * @param banner
     * @param bannerInDb
     * @return
     */
    public Banner updatePojo(Banner banner, Banner bannerInDb) {
        if (banner.getTitle() != null && !"".equals(banner.getTitle())) {
            bannerInDb.setTitle(banner.getTitle());
        }
        if (bannerTypeImage.equals(banner.getType()) || bannerTypeVideo.equals(banner.getType())) {
            bannerInDb.setType(banner.getType());
        }

        if (banner.getUrl() != null && !"".equals(banner.getUrl())) {
            bannerInDb.setUrl(banner.getUrl());
        }
        if (banner.getAreaList() != null && !"".equals(banner.getAreaList())) {
            bannerInDb.setAreaList(banner.getAreaList());
        }
        if (banner.getSort() != null && !"".equals(banner.getSort())) {
            bannerInDb.setSort(banner.getSort());
        }
        bannerInDb.setUpdatedAt(LocalDateTime.now());
        return bannerInDb;
    }
}
